const app = getApp();
let rtcroom = require('../../utils/rtcroom.js');
const getlogininfo = require('../../getlogininfo');

Page({
  /**
     * 页面的初始数据
     */
  data: {
    roomID: '',         // 房间id
    roomname: '',       // 房间名称
    beauty: 5,
    muted: false,
    debug: false,
    inputMsg: '',     // input信息
    comment: [],      // 评论区信息
    frontCamera: true,
    showMap: false,
  },

  onRoomEvent: function (e) {
    switch (e.detail.tag) {
      case 'recvTextMsg':
        {
        /**
             * res:
             * {
             *   roomID: roomInfo.roomID,
             *   userID: msg.fromAccountNick,
             *   nickName: msg.nickName,
             *   headPic: msg.headPic,
             *   textMsg: msg.content,
             *   time: msg.time
	         * }
             */
        console.log('收到消息:', e.detail.detail);
        let msg = JSON.parse(e.detail.detail);
        this.data.comment.push({
          content: msg.textMsg,
          name: msg.nickName,
          time: msg.time,
        });
        this.setData({
          comment: this.data.comment,
          toview: '',
        });
        // 滚动条置底
        this.setData({
          toview: 'scroll-bottom',
        });
        break;
      }
      case 'roomClosed':
        {
        /**
         * 房间关闭时会收到此通知，客户可以提示用户房间已经关闭，做清理操作
          */
        // 在房间内部才显示提示
        const { memberCount } =  e.detail.detail;
        this.closeRoom();
        break;
      }
      case 'error':
        {
        // 在房间内部才显示提示
        console.error('error:', e.detail.detail);
        let pages = getCurrentPages();
        if (pages.length > 1 && (pages[pages.length - 1].__route__ === 'cm_video_alarm/trtc/pages/customer-service-room/customer-service-room')) {
          wx.showModal({
            title: '提示',
            content: e.detail.detail,
            showCancel: false,
            complete: function () {
              pages = getCurrentPages();
              // 点击 modal 后，判断页面是否已跳转，防止跳转两次
              if (pages.length > 1 && (pages[pages.length - 1].__route__ === 'cm_video_alarm/trtc/pages/customer-service-room/customer-service-room')) {
                  wx.navigateBack({
                  delta: 1,
                  });
              }
            },
          });
        }
        break;
      }
    }
  },

  closeRoom: function () {
      this.isComplete().then(res => {
      const pages = getCurrentPages();
      if (pages.length > 1 && pages[pages.length - 1].__route__ === 'cm_video_alarm/trtc/pages/customer-service-room/customer-service-room') {
        wx.navigateBack({
          delta: 1,
      });
    }
    });
  },

  isComplete: function() {
    return new Promise(resolve => {
    app.util.request({
      url: 'entry/wxapp/alarm',
      data: {
        op: 'alarmResolve',
        roomid: this.data.roomID,
      },
      module: 'cm_video_alarm',
        complete: (res) => {
          resolve(true);
        },
      });
        });
  },

  changeCamera: function () {
    let rtcroomCom = this.selectComponent('#rtcroom');
    if (rtcroomCom) {
      rtcroomCom.switchCamera();
    }
    this.setData({
      frontCamera: !this.data.frontCamera,
    });
  },

  setBeauty: function () {
    this.data.beauty = (this.data.beauty == 0 ? 5 : 0);
    this.setData({
      beauty: this.data.beauty,
    });
  },

  changeMute: function () {
    this.data.muted = !this.data.muted;
    this.setData({
      muted: this.data.muted,
    });
  },

  checkDebug: function() {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'checkSwitch',
      },
      module: 'cm_video_alarm',
      success: res => {
        if (res.data && res.data.errno == 0) {
          const data = res.data.data;
          if (data) {
            this.setData({ debug: data.is_debug == 1 });
          }
        }
      },
    });
  },
  
  showLog: function () {
    this.data.debug = !this.data.debug;
    this.setData({
      debug: this.data.debug,
    });
  },

  bindInputMsg: function (e) {
    this.data.inputMsg = e.detail.value;
  },

  sendComment: function(msg) {
    let rtcroomCom = this.selectComponent('#rtcroom');
    if (rtcroomCom) {
      if (this.data.inputMsg && this.data.inputMsg == '?info') {
        // 打印userID和RoomID到聊天窗口
        let time = new Date();
        let h = String(time.getHours());
        let m = String(time.getMinutes());
        let s = String(time.getSeconds());
        h.length == 1 ? (h = '0' + h) : '';
        m.length == 1 ? (m = '0' + m) : '';
        s.length == 1 ? (s = '0' + s) : '';
        time = h + ':' + m + ':' + s;
        let roomInfo = rtcroomCom.getRoomInfo();
        let accountInfo = rtcroomCom.getAccountInfo();
        this.data.comment.push({
          content: '您当前使用的userID为' + accountInfo.userID + ', roomID为' + roomInfo.roomID,
          name: '【本地消息】',
          time: time,
        });
        this.setData({
          comment: this.data.comment,
          toview: '',
        });
        this.setData({
          inputMsg: '',
        });
      } else {
        // 发送消息
        rtcroomCom.sendTextMsg(this.data.inputMsg);
        this.setData({
          inputMsg: '',
        });
      }
    }
  },

  getRoomLocation: function () {
    const self = this;
    app.util.request({
      url: 'entry/wxapp/alarm',
      data: {
        op: 'getCoordinate',
        roomid: this.data.roomID,
      },
      module: 'cm_video_alarm',
      success: function (res) {
        if (res.data && res.data.errno == 0) {
          const data = res.data.data;
          const lat = data ? Number(data.lat) : null;
          const lng = data ? Number(data.lng) : null;
          self.setData({
            latitude: lat,
            longitude: lng,
            markers: [{
                id: 1,
                latitude: lat,
                longitude: lng,
                iconPath: '/cm_video_alarm/Resources/location.png',
            }],
          });
        }
      },
    });
  },

  /**
     * 生命周期函数--监听页面加载
     */
  getlocation() {
    if (this.data.latitude && this.data.longitude) {
      wx.openLocation({
        latitude: this.data.latitude,
        longitude: this.data.longitude,
        scale: 18,
        name: '对方位置',
      });
    } else {
      wx.showToast({
        title: '未获取到对方地理位置',
        icon: 'none',
      });
    }
  },

  changeMap(e) {
    this.setData({ showMap: e.detail.showMap });
  },  

  onLoad: function (options) {
    console.log('room.js onLoad');
    let time = new Date();
    time = time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds();
    console.log('*************开始多人音视频：' + time + '**************');
    this.data.role = options.type;
    this.data.roomID = options.roomID || '';
    this.data.roomname = options.roomName;
    this.data.username = options.userName;
    this.data.isCardEntry = options.isCardEntry||'';
    if (this.data.isCardEntry) {
      getlogininfo.getLoginInfo({
        type: 'multi_room',
        success: ret => {
    this.setData({
      roomID: this.data.roomID,
      roomname: this.data.roomname,
      username: this.data.username,
            isCardEntry: this.data.isCardEntry,
      bjrxm: this.data.roomname ? this.data.roomname : '',
    }, function() {
      let rtcroomCom = this.selectComponent('#rtcroom');
      if (rtcroomCom) {
        rtcroomCom.start().then(roomid => {
          app.util.request({
            url: 'entry/wxapp/alarm',
            data: {
              op: 'alarmProcess',
              roomid,
              worker_id: wx.getStorageSync('userInfo').openid,
            },
            module: 'cm_video_alarm',
          });
          app.util.request({
            url: 'entry/wxapp/alarm',
            data: {
              op: 'postUserId',
              roomid,
              police_user_id: rtcroom.getAccountInfo().userID,
            },
            module: 'cm_video_alarm',
          });
        });
      }
      this.getRoomLocation();
    });
  },
        fail: ret => {
          wx.hideLoading();
          wx.showModal({
            title: '获取登录信息失败',
            content: ret.errMsg,
            showCancel: false,
            complete: function () {
              wx.redirectTo({
                url: 'cm_video_alarm/index/index',
              });
            },
          });
        },
      });
    } else {
      this.setData({
        roomID: this.data.roomID,
        roomname: this.data.roomname,
        username: this.data.username,
        isCardEntry: this.data.isCardEntry,
        bjrxm: this.data.roomname ? this.data.roomname : '',
      }, function () {
        let rtcroomCom = this.selectComponent('#rtcroom');
        if (rtcroomCom) {
          rtcroomCom.start().then(roomid => {
            app.util.request({
              url: 'entry/wxapp/alarm',
              data: {
                op: 'alarmProcess',
                roomid,
                worker_id: wx.getStorageSync('userInfo').openid,
              },
              module: 'cm_video_alarm',
            });
            app.util.request({
              url: 'entry/wxapp/alarm',
              data: {
                op: 'postUserId',
                roomid,
                police_user_id: rtcroom.getAccountInfo().userID,
              },
              module: 'cm_video_alarm',
            });
          });
        }
        this.getRoomLocation();
      });

    }
    this.checkDebug();
  },

  /**
     * 生命周期函数--监听页面初次渲染完成
     */
  onReady: function () {
    let self = this;
    if (!self.versiongt(wx.systemInfo.SDKVersion, '2.7.7')) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，影响正常使用，请升级到最新微信版本后再试。',
        showCancel: false,
        success: res =>{
          self.closeRoom();
        },
      });
      return;
    }

    if (!self.data.username) {
      wx.showModal({
        title: '提示',
        content: '登录信息还未获取到，请稍后再试',
        showCancel: false,
        complete: function () {
          let pages = getCurrentPages();
          if (pages.length > 1 && (pages[pages.length - 1].__route__ === 'cm_video_alarm/trtc/pages/customer-service-room/customer-service-room')) {
            wx.navigateBack({
              delta: 1,
            });
          }
        },
      });
      return;
    }
    // 设置房间标题
    wx.setNavigationBarTitle({
      title: self.data.roomname,
    });

    // 打印userID
    let time = new Date();
    let h = String(time.getHours());
    let m = String(time.getMinutes());
    let s = String(time.getSeconds());
    h.length == 1 ? (h = '0' + h) : '';
    m.length == 1 ? (m = '0' + m) : '';
    s.length == 1 ? (s = '0' + s) : '';
    time = h + ':' + m + ':' + s;

    let rtcroomCom = this.selectComponent('#rtcroom');
    let accountInfo = {};
    if (rtcroomCom) {
      accountInfo = rtcroom.getAccountInfo();
    }
    // accountInfo
    // {
    //     userID,			// 用户ID
    //     userName,		// 用户昵称
    //     userAvatar,		// 用户头像URL
    //     userSig,		// IM登录凭证
    //     sdkAppID,		// IM应用ID
    //     accountType,	// 账号集成类型
    //     accountMode,		//帐号模式，0-表示独立模式，1-表示托管模式
    //     token			//登录RoomService后使用的票据
    // }
    this.data.comment.push({
      content: '您当前使用的userID为' + accountInfo.userID,
      name: '【本地消息】',
      time: time,
    });
    this.setData({
      comment: this.data.comment,
      toview: '',
    });
  },

  /**
     * 生命周期函数--监听页面显示
     */
  onShow: function () {
    let self = this;
    console.log('room.js onShow');
    // 保持屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
  },

  /**
     * 生命周期函数--监听页面隐藏
     */
  onHide: function () {
    let self = this;
    console.log('room.js onHide');
  },

  /**
     * 生命周期函数--监听页面卸载
     */
  onUnload: function () {
    console.log('room.js onUnload');
    this.closeRoom();
  },

  /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
  onPullDownRefresh: function () {

  },

  /**
     * 页面上拉触底事件的处理函数
     */
  onReachBottom: function () {

  },

  versiongt: function (version1, version2) {
    var v1 = version1.split(".");
    var v2 = version2.split(".");
    if (parseInt(v1[0]) > parseInt(v2[0])) {
      return true;
    } else if (parseInt(v1[0]) == parseInt(v2[0])) {
      if (parseInt(v1[1]) > parseInt(v2[1])) {
        return true;
      } else if (parseInt(v1[1]) == parseInt(v2[1])) {
        if (parseInt(v1[2]) >= parseInt(v2[2])) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
});
